<template>
  <div class="gems-collapse">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import { ref, provide, watch } from 'vue'
import type { CollapseProps, NameType } from './types'
import { collapseContextKey } from './types'

defineOptions({
  name: 'GemsCollapse'
})

const props = defineProps<CollapseProps>()
const emits = defineEmits(['update:modelValue', 'change'])

// 维护一个数组--保存当前激活的面板name
const activeNames = ref<NameType[]>(props.modelValue || [])
// 本地向组件传值props,组件用ref接收,注意要监听
watch(
  () => props.modelValue,
  () => {
    activeNames.value = props.modelValue
  }
)

// 手风琴模式
if (props.accordion && activeNames.value.length > 1) {
  console.warn('accordion mode should only have one acitve item')
}

const handleItemClick = (item: NameType) => {
  let _activeNames = [...activeNames.value ]
  if (props.accordion) {
    _activeNames = item === activeNames.value[0] ? [] : [item]
    activeNames.value = _activeNames
  } else {
    const index = _activeNames.indexOf(item)
    // 如果当前点击的面板未激活，则添加
    if (index === -1) {
      _activeNames.push(item)
    } else {
      // 如果当前点击的面板已激活，则移除
      _activeNames.splice(index, 1)
    }
    activeNames.value = _activeNames
  }
  // 向父组件传递当前激活的面板数组
  emits('update:modelValue', _activeNames)
  emits('change', _activeNames)
}

provide(collapseContextKey, {
  activeNames,
  handleItemClick
})
</script>
